{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "*saved from internet archive:https://web.archive.org/web/20160402152249/http://nerds.weddingpartyapp.com/tech/2015/01/21/rxjava-share-publish-refcount-and-all-that-jazz/*:\n",
    "\n",
    "\n",
    "Ok, so in my previous post I innocuously introduced the `.share()` operator.\n",
    "\n",
    "```java\n",
    "Observable<Object> tapEventEmitter = _rxBus.toObserverable().share();\n",
    "```\n",
    "\n",
    "# What is this share operator?\n",
    "The `.share()` operator is basically just a wrapper to the chained call `.publish().refcount()`.\n",
    "\n",
    "You’ll find the chained combo `.publish().refcount()` used in quite a few Rx examples on the web. It allows you to “share” the emission of the stream. Considering how powerpacked and frequently used this combo is, RxJava basically introduced the friendlier more useful operator share(). This mechanism of using observables is sometimes referred to as “multicasting”.\n",
    "\n",
    "Let’s dig into some of the basics first:\n",
    "\n",
    "> “ConnectedObservable” – This is a kind of observable which doesn’t emit items even if subscribed to. It only starts emitting items after its .connect() method is called.\n",
    "\n",
    "It is for this reason that a connected obesrvable is also considered **“cold”** or “inactive” before the connect method is invoked.\n",
    "\n",
    "> `.publish()`– This method allows us to change an ordinary observable into a “ConnectedObservable”. Simply call this method on an ordinary observable and it becomes a connected one.\n",
    "\n",
    "We now know what ½ of the operator `share` does. Now why would you ever use a Connected Observable? The docs say:\n",
    "\n",
    "> In this way you can wait for all intended Subscribers to subscribe to the Observable before the Observable begins emitting items.\n",
    "\n",
    "This essentially means that a regular usecase for `publish` would involve more than one subscriber. When you have more than one subscriber, it can get tricky to handle each of the subscriptions and dispose them off correctly. To make this process easier, Rx introduced this magical operator called `refcount()`:\n",
    "\n",
    "\n",
    "> `refcount()` – This operator keeps track of how many subscribers are subscribed to the resulting Observable and refrains from disconnecting from the source ConnectedObservable until all such Observables are unsubscribed.\n",
    "\n",
    "It essentially maintains a reference counter in the background and accordingly takes the correct action when a subscription needs to be unsubscribed or disposed off. This is the second ½ of the operator share. You are now armed with knowledge of what each of those terms mean.\n",
    "\n",
    "\n",
    "Let’s look at the example from debouncedBuffer again and see how share was used there:\n",
    "\n",
    "\n",
    "```\n",
    "Observable<Object> tapEventEmitter = _rxBus.toObserverable().share();\n",
    "// which is really the same as:\n",
    "Observable<Object> tapEventEmitter = _rxBus.toObserverable().publish().refcount();\n",
    "```\n",
    "\n",
    "We now have a “shareable” observable called “tapEventEmitter” and because it’s sharable and still not yet ‘live’ (publish from the share call changes it to a ConnectedObservable), we can use it to compose our niftier Observables and rest assured that we always have a reference to the original observable (the original observable being `_rxBus.toObserverable()` in this case).\n",
    "\n",
    "\n",
    "```\n",
    "Observable<Object> tapEventEmitter = _rxBus.toObserverable().share();\n",
    "Observable<Object> debouncedEventEmitter = tapEventEmitter.debounce(1, TimeUnit.SECONDS);\n",
    "tapEventEmitter.buffer(debouncedEventEmitter)\n",
    "//...\n",
    "```\n",
    "\n",
    "All this sounds good. There is however a possible **race condition** with this implementation (which Ben [pointed out](https://gist.github.com/benjchristensen/e4524a308456f3c21c0b#comment-1367814) through a comment on this gist).\n",
    "\n",
    "The race condition occurs because there are two subscribers here (debounce and buffer) and they may come and go at different points. Remember that the RxBus is backed by a hot/live Subject which is constantly emitting items. By using the share operator we guarantee a reference to the same source, but NOT that they’ll receive the exact same items if the subscribers enter at different points of time. Ben explains this well:\n",
    "\n",
    "\n",
    "> The race condition is when the two consumers subscribe. Often on a hot stream it doesn’t matter when subscribers come and go, and refCount is perfect for that. The race condition refCount protects against is having only 1 active subscription upstream. However, if 2 Subscribers subscribe to a refcounted stream that emits 1, 2, 3, 4, 5, the first may get 1, 2, 3, 4, 5 and the second may get 2, 3, 4, 5.\n",
    "> To ensure all subscribers start at exactly the same time and get the exact same values, refCount can not be used. Either ConnectableObservable with a manual, imperative invocation of connect needs to be done, or the variant of publish(function) which connects everything within the function before connecting the upstream.\n",
    "\n",
    "\n",
    "In our usage it’s almost immediate so it probably wouldn’t matter a whole lot. But our original intention was to have the debouncedBuffer function as a single operator. It seems conceptually incorrect if the same events are not emitted. I added a third improved implementation to handle this race condition using Ben’s latter suggestion:\n",
    "\n",
    "```\n",
    "// don't start emitting items just yet by turning the observable to a connected one\n",
    "ConnectableObservable<Object> tapEventEmitter = _rxBus.toObserverable().publish();\n",
    "\n",
    "tapEventEmitter.publish((Func1) (stream) -> {\n",
    "\n",
    "    // inside `publish`, \"stream\" is truly multicasted\n",
    "\n",
    "    // applying the same technique for getting a debounced buffer sequence\n",
    "    return stream.buffer(stream.debounce(1, TimeUnit.SECONDS));\n",
    "\n",
    "}).subscribe((Action1) (taps) {\n",
    "    _showTapCount(taps.size());\n",
    "});\n",
    "\n",
    "// start listening to events now\n",
    "tapEventEmitter.connect();\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
